# gozerbot/myimport.py
#
#

""" use the imp module to import modules. """

__copyright__ = 'this file is in the public domain'

# ==============
# IMPORT SECTION 

# basic import
from gozerbot.utils.log import rlog
from gozerbot.utils.locking import lockdec

import time, sys, imp, os, thread

# END IMPORT 
# ==========

# ============
# LOCK SECTION

gozerimportlock = thread.allocate_lock()
locked = lockdec(gozerimportlock)

# END LOCK
# ========

#@locked
def gozer_import(name, path=None):

    """
        import module <name> with the imp module  .. will reload module is 
        already in sys.modules.

        :param name: name of the module to import (may contain dots)
        :type name: string
        :param path: optional path to search in
        :type path: string
        :rtype: module

        .. literalinclude:: ../../gozerbot/gozerimport.py
            :pyobject: gozer_import

    """

    rlog(1, 'gozerimport', 'importing %s' % name)

    splitted = name.split('.')
    
    for plug in splitted:
        fp, pathname, description = imp.find_module(plug, path)
        try:
           result = imp.load_module(plug, fp, pathname, description)
           try:
               path = result.__path__
           except:
               pass
        finally:
            if fp:
                fp.close()

    if result:
        return result

#@locked
def force_import(name):

    """
        force import of module <name> by replacing it in sys.modules.

        :param name: name of module to import
        :type name: string
        :rtype: module

        .. literalinclude:: ../../gozerbot/gozerimport.py
            :pyobject: force_import

    """

    try:
        del sys.modules[name]
    except KeyError:
        pass
    plug = gozer_import(name)
    if plug:
        sys.modules[name] = plug
        return plug

# ============
# INIT SECTION

# no vars

# END INIT
# ========
